package lab2;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.File;

public class DigestProcessor
{
	private String [] files;
	
	protected void processArgs(String [] args)
	{
		for(int i = 0; i < args.length; i++)
		{
			File file = new File (args[i]);
			
			if(file.exists())
			{
				try
				{
					FileInputStream fis = new FileInputStream (file);
					this.createDigest(fis, file);
					fis.close();
				} catch (FileNotFoundException e)
				{
					// TODO Auto-generated catch block
					System.out.println ("Failed to create FileInputStream for: "+file.getPath());
				} catch (IOException e)
				{
					System.out.println("Failed to close FileInputStream for: "+file.getPath());
				}
			}
			else
			{
				System.out.println("File "+file.getPath()+" does not exist!");
			}			
		}
	}
	
	protected void printDigestOutput (byte[] arr, String path)
	{
		System.out.print(path);
		System.out.print(": ");
		
		for(int i = 0; i < arr.length; i++)
		{
			System.out.print((int)arr[i]);
			System.out.print(" ");
		}
		System.out.print("\n");
	}
	
	public void processArgs ()
	{
		this.processArgs(this.files);
	}
		
	protected void getUserInput()
	{
		//TODO: implement this
		System.out.println("Not implemented");
	}
	
	protected void createDigest(FileInputStream fis, File file)
	{
		try
		{
			MessageDigest sha;
			sha = MessageDigest.getInstance("SHA");
	      	DigestInputStream din = new DigestInputStream(fis, sha);
	        
	      	while ((din.read()) != -1); 
	      	
	      	din.close();
	      	
	      	byte[] digest = sha.digest();
	      	this.printDigestOutput(digest, file.getPath());
	      	      	
		} catch (NoSuchAlgorithmException e)
		{
			// wel should not get here leaving auto generated code
			e.printStackTrace();
		} catch (IOException e)
		{
			//dido, by this time the file should already be good and stuff.
			e.printStackTrace();
		}
		
	}
	
	public DigestProcessor (String [] args)
	{
		this.files = args;
	}
	
	public DigestProcessor ()
	{
		this.getUserInput();
	}
	
}
